/*
reducer函数模块: 根据当前state和指定action返回一个新的state
 */
import {combineReducers} from 'redux'
import {RECEIVE_USER,SHOW_ERROR_MSG,RESET_USER,SET_HEAD_TITLE, SET_HEAD_TITLE_ARREYS} from './action_types'
import storageUtils from '../utils/storageUtils'

/**管理headertitleArreys数据的reducer */
const initHeadTitleArreys = [{title:'首页111',key:'/home'}]
const titleArrays=[]
function removeEmptyField(obj) {
  var newObj = {};
  if(typeof obj == "string"){
      obj = JSON.parse(obj);
  }
  if(obj instanceof Array){
      newObj = [];
  }
  if(obj instanceof Object){
      for(var attr in obj){
          if(obj.hasOwnProperty(attr) && obj[attr] !== "" && obj[attr] !== null && obj[attr] !== undefined){
              if(obj[attr] instanceof Object){
                  newObj[attr] = removeEmptyField(obj[attr]);
              }else if(typeof obj[attr] == "string" && ((obj[attr].indexOf("{") > -1 && obj[attr].indexOf("}") > -1) || (obj[attr].indexOf("[") > -1 && obj[attr].indexOf("]") > -1))){
                  try{
                      var attrObj = JSON.parse(obj[attr]);
                      if(attrObj instanceof Object){
                          newObj[attr] = removeEmptyField(attrObj);
                      }
                  }catch (e){
                      newObj[attr] = obj[attr];
                  }
              }else{
                  newObj[attr] = obj[attr];
              }
          }
      }
  }
  return newObj;
}
function headTitleArreys(state = initHeadTitleArreys, action) {
  // console.log( action)
  titleArrays.push({headTitleArreys:action.data})
  removeEmptyField(titleArrays)
  switch (action.type) {
    case SET_HEAD_TITLE_ARREYS:
      return  titleArrays
    default:
      return state
  }
}

/**管理headertitle状态数据的reducer */
const initHeadTitle = '首页'

function headTitle(state = initHeadTitle, action) {
  // console.log('headTitle()', state, action)
  switch (action.type) {
    case SET_HEAD_TITLE:
      return action.data
    default:
      return state
  }
}
 /*
管理user状态数据的reducer
 */
const initUser =  storageUtils.getUser()
 function user(state=initUser,action){
    switch (action.type) {
        case RECEIVE_USER:
           return action.user
        case SHOW_ERROR_MSG:
            return {errorMsg:action.errorMsg}
        case RESET_USER:
            return {}
        default:
            return state;
    }
 }

 /*
向外暴露合并后产生的总reducer函数
总的state的结构:
  {
    headerTitle: '',
    user: {}
  }
 */
export default combineReducers({
    user,
    // headerTitle
    headTitle,
    headTitleArreys
})